package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.UserService;
import com.sky.service.WorkSpaceService;
import com.sky.utils.TimeForDataUtil;
import com.sky.utils.WeChatLoginUtil;
import com.sky.vo.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Min;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@AllArgsConstructor
public class WorkSpaceServiceImpl implements WorkSpaceService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private ReportService reportService;
    @Autowired
    private UserService userService;


    public DishOverViewVO getDisheStatus() {
        DishOverViewVO disheStatus = dishMapper.getDisheStatus();
        return DishOverViewVO.builder().discontinued(disheStatus.getDiscontinued()).sold(disheStatus.getSold()).build();
    }


    public OrderOverViewVO getOrderStatus() {
        OrderOverViewVO orderStatus = orderMapper.getOrderStatus();
        return OrderOverViewVO.builder()
                .allOrders(orderStatus.getAllOrders())
                .cancelledOrders(orderStatus.getCancelledOrders())
                .completedOrders(orderStatus.getCompletedOrders())
                .waitingOrders(orderStatus.getWaitingOrders())
                .deliveredOrders(orderStatus.getDeliveredOrders())
                .build();
    }


    public SetmealOverViewVO getSetmealStatus() {
        SetmealOverViewVO setmealStatus = setmealMapper.getSetmealStatus();
        return SetmealOverViewVO.builder().discontinued(setmealStatus.getDiscontinued()).sold(setmealStatus.getSold()).build() ;
    }

    public BusinessDataVO getBusinessData(LocalDate begin, LocalDate end) {
        OrderReportVO orderReport = reportService.getOrderReport(begin, end);
        TurnoverReportVO turnoverReport = reportService.getTurnoverReport(begin, end);
        UserReportVO userStatistics = userService.getUserStatistics(begin, end);



        // 处理 turnoverList，将其拆分为单个数字并求和
        double turnoverSum = 0.0;
        if (turnoverReport.getTurnoverList() != null && !turnoverReport.getTurnoverList().isEmpty()) {
            String[] turnoverValues = turnoverReport.getTurnoverList().split(",");
            for (String value : turnoverValues) {
                if (!value.isEmpty()) {
                    turnoverSum += Double.parseDouble(value);
                }
            }
        }

        // 处理 newUsersList，将其拆分为单个数字并求和
        int newUsersSum = 0;
        if (userStatistics.getNewUserList() != null && !userStatistics.getNewUserList().isEmpty()) {
            String[] newUsersValues = userStatistics.getNewUserList().split(",");
            for (String value : newUsersValues) {
                if (!value.isEmpty()) {
                    newUsersSum += Integer.parseInt(value);
                }
            }
        }
        Double unitPrice = 0.0;
        Integer validOrder = orderReport.getValidOrderCount();

        if (validOrder != 0) {
            unitPrice = turnoverSum / validOrder;
        }

        log.info("orderReport：{}", orderReport);
        log.info("turnoverReport：{}", turnoverReport);
        log.info("userStatistics：{}", userStatistics);

        return BusinessDataVO.builder()
                .newUsers(newUsersSum)
                .orderCompletionRate(orderReport.getOrderCompletionRate())
                .turnover(turnoverSum)
                .unitPrice(unitPrice)
                .validOrderCount(orderReport.getValidOrderCount())
                .build();
    }
    public void exportBussinessData(HttpServletResponse response) throws IOException {
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //获取概览数据
        BusinessDataVO businessData = getBusinessData(dateBegin, dateEnd);
        //通过POI将数据写入Excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(in);

        XSSFSheet sheetAt = excel.getSheetAt(0);
        //填充时间
        sheetAt.getRow(1).getCell(1).setCellValue("时间" + dateBegin + "至" + dateEnd);
        //填充营业额
        sheetAt.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
        //填充完成率
        sheetAt.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
        //填充新用户
        sheetAt.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
        //填充有效订单
        sheetAt.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
        //填充有效订单
        sheetAt.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

        //明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date = dateBegin.plusDays(i);
            BusinessDataVO businessDataDetail =
                     getBusinessData(date, date);

            XSSFRow row = sheetAt.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessDataDetail.getTurnover());
            row.getCell(3).setCellValue(businessDataDetail.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataDetail.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDataDetail.getUnitPrice());
            row.getCell(6).setCellValue(businessDataDetail.getNewUsers());
        }

        ServletOutputStream out = response.getOutputStream();
        //关闭资源
        excel.write(out);
        out.close();
        excel.close();

    }
}
